package com.sgzn.sgpay.service.support;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;


/**
 * @author huanghuanming
 * @version Id; HttpClientUtils, 2018/5/4 14:27 huanghuanming Exp $$
 */
@Slf4j
public class HttpClientUtils {

    private static PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager();
    private static CloseableHttpClient httpClient = null;
    private static final int DEFAULT_MAX_TOTAL_CONNECTION = 1024;
    private static final int DEFAULT_MAX_PER_ROUTE = 50;

    private static final int DEFAULT_CONNECT_TIMEOUT = 6000;
    private static final int DEFAULT_SOCKET_TIMEOUT = 6000;
    private static final int DEFAULT_CONNECTION_REQUEST_TIMEOUT = 6000;
    private static final String DEFAULT_ENCODE = "UTF-8";
    private static final String DEFAULT_CONTENT_TYPE = "application/json";


    private static final HttpClientOption defaultHttpClientOption = new HttpClientOption();

    static {
        log.info("HttpClientUtils init start:");
        poolingHttpClientConnectionManager.setMaxTotal(DEFAULT_MAX_TOTAL_CONNECTION);
        poolingHttpClientConnectionManager.setDefaultMaxPerRoute(DEFAULT_MAX_PER_ROUTE);
        
        httpClient = HttpClients.custom().setConnectionManager(poolingHttpClientConnectionManager).build();

        defaultHttpClientOption.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT);
        defaultHttpClientOption.setSocketTimeout(DEFAULT_SOCKET_TIMEOUT);
        defaultHttpClientOption.setConnectionRequestTimeout(DEFAULT_CONNECTION_REQUEST_TIMEOUT);

        defaultHttpClientOption.setEnCode(DEFAULT_ENCODE);
        defaultHttpClientOption.setContentType(DEFAULT_CONTENT_TYPE);

        log.info("HttpClientUtils init  end:");
    }


    /**
     *发送post请求
     *
     * @param url
     * @param content
     * @return
     */
    public static String post(String url, String content) throws Exception{

        HttpClientOption httpClientOption = new HttpClientOption();

        return post(url, content, httpClientOption);
    }


    /**
     * 发送post请求
     * @param url
     * @param content
     * @param clientOption
     * @throws Exception
     * @return
     */
    public static String post(String url, String content, HttpClientOption clientOption) throws Exception{

        log.info("send http request:"+url);

        HttpClientOption httpClientOption = clientOption ;

        if(httpClientOption==null){
            httpClientOption = defaultHttpClientOption;
        }

        String responseString = null;
        HttpPost httpPost = null;
        CloseableHttpResponse response = null;
        HttpEntity respEntity = null;
        try {
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(httpClientOption.getConnectTimeout())
                    .setConnectionRequestTimeout(httpClientOption.getConnectionRequestTimeout()).setSocketTimeout(httpClientOption.getSocketTimeout()).build();
            httpPost = new HttpPost(url);
            httpPost.setConfig(requestConfig);
            StringEntity entity = new StringEntity(content, httpClientOption.getEnCode());// 解决中文乱码问题

            if(StringUtils.isNotBlank(httpClientOption.getEnCode())){
                entity.setContentEncoding( httpClientOption.getEnCode());
            }

            if(StringUtils.isNotBlank(httpClientOption.getContentType())){
                entity.setContentType(httpClientOption.getContentType());
            }

            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost);

            respEntity = response.getEntity();

            if (respEntity != null) {
                responseString = EntityUtils.toString(respEntity, httpClientOption.getEnCode());
            }

        } catch (Exception e) {
            log.info(String.format("[HttpClientUtils.error] url:%s", url), e);
            throw e;
        } finally {
            if (httpPost != null) {
                httpPost.releaseConnection();
            }
            if(response!=null){
                response.close();
            }
            if(respEntity!=null && respEntity.getContent()!=null){
                respEntity.getContent().close();
            }
        }

        return responseString;
    }

    private HttpClientUtils() {
        throw new IllegalStateException("Utility class");
    }

}
